<template>
  <div class="flexContent">
    <div class="searchBox">
      <!-- 期初库存报表 -->
      <el-form class="demo-form-inline" label-position="left" label-width="auto">
        <div class="serFlexBox">
          <div class="inputBox">
            <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="门店">
                  <el-select v-model="sForm.storeId" @click.native="getShopAllList" filterable clearable
                    popper-class="eloption" style="width: 95%;" placeholder="请选择">
                    <el-option v-for="shop in shopListTwo" :key="shop.id" :value="shop.id" :label="shop.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                <el-form-item label="商品">
                  <el-input v-clearEmoji v-model.trim="sForm.name" size="small" clearable style="width: 95%;"
                    placeholder="请输入" @keyup.enter.native="searchFn" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="btnBox">
            <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
            <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="add">
      <el-button class="addBtn" v-has="'goods_add'" @click="exportFn">导出</el-button>
    </div>
    <div class="table" id="tableBox" v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{ resizable: true }" border class="tablebox" ref="xTable1"
          :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%" height="98%"
          size="medium" align="center" :footer-method="getSummaries" show-footer>
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="storeNum" title="门店编号" :min-width="elTableAdaptationWidth('storeNum', stockReportList)" />
          <vxe-column field="storeName" title="门店名称" :min-width="elTableAdaptationWidth('storeName', stockReportList)" />
          <vxe-column field="name" title="商品名称" :min-width="elTableAdaptationWidth('name', stockReportList)" />
          <vxe-column field="firstCode" title="商品条码" :min-width="elTableAdaptationWidth('firstCode', stockReportList)" />
          <vxe-column field="standard" title="规格" min-width="150" />
          <vxe-column field="unitName" title="单位" width="100" />
          <vxe-column field="outboundPrice" title="出仓价（元）" min-width="150" />
          <vxe-column field="storePrice" title="售价（元）" min-width="150" />
          <vxe-column field="initialInventory" title="期初库存" min-width="150" />
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,-> , sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getStockReportList, exportInitial } from "@/api/report";
import { getShopEasy } from "@/api/shop";
export default {
  name: "initialReport",
  data() {
    return {
      sForm: {
        storeId: '',
        name: '',
      },
      stockReportList: [],
      shopListTwo: [],
      isSearch: false,
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      allDataArr: [],
      fieldSort: ['seq', 'storeNum', 'storeName', 'name', 'firstCode', 'standard', 'unitName', 'outboundPrice', 'storePrice', 'initialInventory']
    };
  },
  created() {
    this.getStockReportList();
    this.getShopAllList();
  },
  methods: {
    async getStockReportList() {
      if (!this.isSearch) {
        this.sForm = {
          storeId: '',
          name: '',
        }
      }
      const res = await getStockReportList({
        ...this.page,
        ...this.sForm
      });
      if (res.code === 200) {
        console.log(res);
        let sum = res.data.sum;
        const result = res.data.pageInfo;
        this.stockReportList = result.list;
        this.page.pageSize = result.pageSize;
        this.page.pageNum = result.pageNum;
        this.page.total = result.total;
        console.log("shopList", this.stockReportList);
        let resArr = [];
        this.allDataArr = [];
        this.fieldSort.forEach(e => {
          if (e == 'initialInventory') {
            resArr.push(sum)
          } else if (e == 'seq') {
            resArr.push('合计')
          } else {
            resArr.push('-');
          }
        })
        this.allDataArr.push(resArr);
        const $table = this.$refs.xTable1
        $table.loadData(this.stockReportList);
      } else {
        // this.$message.error(res.message);
      }
    },
    getSummaries() {
      return this.allDataArr;
    },
    async getShopAllList() {
      const res = await getShopEasy()
      if (res.code === 200) {
        this.shopListTwo = res.data.store;
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getStockReportList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getStockReportList();
    },
    async searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getStockReportList();
    },
    resetFn() {
      this.sForm = {
        storeId: '',
        name: '',
      }
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = false;
      this.getStockReportList();
    },
    async exportFn() {
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (!this.isSearch) {
          this.sForm = {
            storeId: '',
            name: '',
          }
        }
        const response = await exportInitial({
          ...this.sForm
        })
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.txtBox {
  padding-left: 20px;
  margin-bottom: 30px;

}

.btnBOX {
  text-align: center;
}
</style>
